<?php

namespace App\Http\Middleware;

use App\Http\Controllers\Constant\Constant;
use App\Http\Controllers\OATrait\OATrait;
use Closure;
use Illuminate\Support\Facades\Cache;

class CheckRequest
{
    use OATrait;
    //白名单
    protected $white_list = array(
        'oa/login',//登录页面
        'oa/checkLogin',//验证登录
        'oa/setUser',
        'oa/staff/staff_position_role',
        'oa/uploadFiles',
        'oa/resetPwd',//修改密码
        'oa/downloadFiles'//下载文件
    );
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //TODO自己的逻辑
        $path = $request->path();
        $ip = $request->ip();
        //if($ip == '127.0.0.1') return $next($request);
        if(in_array($path,$this->white_list))  return $next($request);
           //验证token
            try{
               $token = $request->header('Authorization','');
               if(!Cache::has($token)) throw new \Exception('token不存在');
                $user = $this->getUserByToken($token);
                if($user) {
                    $user['roleid'] = $user['position_id'];
                    $user['deptid'] = $user['dept_id'];
                    $user['is_pm'] = in_array($user['roleid'],Constant::MANAGER_LIST);
                    $request->merge($user);
                }
            }catch (\Exception $e){
               return response()->json(['state'=>'err','msg'=>$e->getMessage()]);
            }


        return $next($request);
    }


}
